class SearchesController < ApplicationController
  before_filter :login_required, :except => [ :index, :show ]
  
  # GET /searches
  # GET /searches.xml
  def index
    @searches = Search.find(:all, :order => 'updated_at DESC')

    respond_to do |format|
      format.html # index.rhtml
      format.xml  { render :xml => @searches.to_xml }
    end
  end

  # GET /searches/1
  # GET /searches/1.xml
  def show
    @search = Search.find(params[:id])
    @content_for_title = @search.keywords
    
    respond_to do |format|
      format.html # show.rhtml
      format.xml  { render :xml => @search.to_xml }
    end
  end

  # GET /searches/new
  def new
    @search = Search.new
  end

  # GET /searches/1;edit
  def edit
    @search = Search.find(params[:id])
  end

  # POST /searches
  # POST /searches.xml
  def create
    respond_to do |format|
      if current_user.searches << @search = Search.find_or_create_by_keywords(params[:search][:keywords])
        format.html { redirect_to search_url(@search) }
        format.xml  { head :created, :location => search_url(@search) }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @search.errors.to_xml }
      end
    end
  end

  # PUT /searches/1
  # PUT /searches/1.xml
  def update
    @search = Search.find(params[:id])

    respond_to do |format|
      if @search.update_attributes(params[:search])
        flash[:notice] = 'Search was successfully updated.'
        format.html { redirect_to search_url(@search) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @search.errors.to_xml }
      end
    end
  end

  # DELETE /searches/1
  # DELETE /searches/1.xml
  def destroy
    @search = Search.find(params[:id])
    @search.destroy

    respond_to do |format|
      format.html { redirect_to searches_url }
      format.xml  { head :ok }
    end
  end
  
  def authorized?
    %w(create index).include?(action_name) || admin?
  end
end
